package main;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import core.Totp;
import core.UpdatePassword;
import cron.CronJob;
import dao.AccountInfo;
import dao.ProxyConfig;
import dao.Result;
import okhttp3.Response;
import utils.*;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URLEncoder;
import java.util.*;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class MyStart {

    public static String addr_security;
    public static String addr_gamecenter;
    public static String addr_notify;


    private static HashMap kafkaConfig = new HashMap<>();
    public static HashMap nacosConfig = new HashMap<>();
    private static HashMap zingSpeedGameId = new HashMap<>();
    public static HashMap garenaGameId = new HashMap<>();

    static LoggerUtile logger =LoggerUtile.getLogger("garenaJava-app");


    public static void start(String env) {

        if("test".equals(env)){
            kafkaConfig.put("clientId","garena-security");
            kafkaConfig.put("bootstrapServers","10.0.80.215:9092");
            nacosConfig.put("serverAddr","10.0.80.214:8848");
            nacosConfig.put("namespace","test");
            nacosConfig.put("username","nacos");
            nacosConfig.put("password","nacos");
            nacosConfig.put("accessToken","5ad9ba4e4a18d81457c3a8286e134f05");
            zingSpeedGameId.put("zingSpeedGameId",new int[]{32773});
            garenaGameId.put("garenaGameId",new int[]{788, 816, 32775});
        } else if ("dev".equals(env)) {
            kafkaConfig.put("clientId","garena-security");
            kafkaConfig.put("bootstrapServers","10.0.80.215:9092");
            nacosConfig.put("serverAddr","");
            nacosConfig.put("namespace","test");
            nacosConfig.put("username","nacos");
            nacosConfig.put("password","nacos");
        } else if ("prod".equals(env)) {
            kafkaConfig.put("clientId","garena-security");
            kafkaConfig.put("bootstrapServers","10.0.85.118:9092");
            nacosConfig.put("serverAddr","10.0.85.121:8848");
            nacosConfig.put("namespace","prod");
            nacosConfig.put("accessToken","18146199dd10039f608c4bafafba6de8");
            nacosConfig.put("username","nacos");
            nacosConfig.put("password","nxcdqRr2WxQcEhcS");
            zingSpeedGameId.put("zingSpeedGameId",new int[]{7933});
            garenaGameId.put("garenaGameId",new int[]{788, 7943, 7956, 7957, 7959, 7960});
        }else {
            logger.error("环境异常，请重试！");
            return;
        }
        new Thread(()->{
            try {
                logger.info("开始启动7.1...");
                createKafkaConnect();
                logger.info("7.1 kafka connect succeeded...");
                createNacosConnect().get();
                logger.info("7.1 nacos connect succeeded...");
              //  createRedisConnect().get();
              //  logger.info("redis connect succeeded...");
                logger.info("7.1 start corn job...");
                runCornJob(env);
            } catch (Exception e) {
                logger.error("Error: " + e.getMessage());
            }
        }).start();
    }

    public static void createKafkaConnect() {
            logger.info("kafka开始链接");
            String bootstrapServers = (String) kafkaConfig.get("bootstrapServers"); // 设置 Kafka 服务器地址
            String id = (String) kafkaConfig.get("clientId"); // 设置 Kafka 服务器地址
            KafkaClient kafkaClient = new KafkaClient(bootstrapServers,id);
            // 创建 Kafka 连接
            kafkaClient.createKafkaConnect();
            // 发送消息到 Kafka
            //kafkaClient.sendMessage("appLogs","测试tttttt");
            // 关闭 Kafka 连接
            kafkaClient.close();
    }

    public static CompletableFuture<Void> createNacosConnect() {
        return CompletableFuture.runAsync(() -> {
            try {
                Properties properties = new Properties();
                properties.put("serverAddr", (String) nacosConfig.get("serverAddr"));
                properties.put("namespace", (String) nacosConfig.get("namespace"));
                properties.put("username", (String) nacosConfig.get("username"));
                properties.put("password", (String) nacosConfig.get("password"));
                logger.info("properties:" + JSON.toJSONString(properties));
                NamingService namingService = NamingFactory.createNamingService(properties);
                List<Instance> instances = namingService.getAllInstances("uggame-service-security");
                List<Instance> instances2 = namingService.getAllInstances("uggame-service-gamecenter");
                List<Instance> instances3 = namingService.getAllInstances("uggame-service-notify");
                List<Instance> instances4 = namingService.getAllInstances("uggame-service-uiautomator2");
                for(Instance instance : instances) {
                    String ip = instance.getIp();
                    int port = instance.getPort();
                    addr_security = ip + ":" + port;
                }
                logger.info("addr_security:" + addr_security);
                for (Instance instance : instances2) {
                    String ip = instance.getIp();
                    int port = instance.getPort();
                    addr_gamecenter = ip + ":" + port;
                }
                logger.info("addr_gamecenter:" + addr_gamecenter);
                for (Instance instance : instances3) {
                    String ip = instance.getIp();
                    int port = instance.getPort();
                    addr_notify = ip + ":" + port;
                }
                logger.info("addr_notify:" + addr_notify);
            } catch (NacosException e) {
                e.printStackTrace();
                logger.info("nacos获取ip异常:" + e.getMessage());
            }
        });
    }

    public static CompletableFuture<Void> createRedisConnect() {
        return CompletableFuture.runAsync(() -> {

            Properties properties = new Properties();
            properties.put("serverAddr", (String) nacosConfig.get("serverAddr"));
            properties.put("namespace", (String) nacosConfig.get("namespace"));
            properties.put("username", (String) nacosConfig.get("username"));
            properties.put("password", (String) nacosConfig.get("password"));

            // 创建 RedisService 实例
            RedisService redisService = new RedisService(properties);

            try {
                logger.info("Redis开始创建链接");
                // 创建 Redis 连接
                redisService.createConnect();

                // 关闭连接
                redisService.getJedis().close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    public static void runCornJob(String env) {
        // Java equivalent of runCornJob
        CronJob cronJob = new CronJob();
        cronJob.strat();
//        loop();
    }

    public static void main(String[] args) {
        /*AccountInfo accountInfo = new AccountInfo("koomgo3","@UghhjtriG1",null,"6BX7YGSAJW47GIGF","111","333");
        UpdatePassword updatePassword = new UpdatePassword();
        ProxyConfig proxyConfig = new ProxyConfig("127.0.0.1", 7890);
        //Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 7890));
        Result result = updatePassword.start(accountInfo,proxyConfig,0, MyStart.addr_security, MyStart.addr_gamecenter);
        System.out.println(result.getData());*/
        start("prod");
//        loop();
    }

    private static ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

    public static void loop(){
        Demo demo = new Demo();
        scheduledExecutorService.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                try {
                    demo.getVpnIp2();
                } catch (Exception e){
//                    System.out.println("执行任务出现异常:"+e.getMessage());
                    logger.info( "执行任务出现异常:"+e.getMessage());
                }

            }
        }, 0, 10, TimeUnit.SECONDS);
    }



}
